<template>
  <div class="viewer-card bg-white/80 backdrop-blur-lg rounded-2xl shadow-md overflow-hidden p-6 transition-all duration-300 ease-in-out">

    <div class="flex items-center justify-between mb-5">
      <h2 class="text-xl font-bold text-gray-800 flex items-center">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-2 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
        <span>看过我</span>
        <span class="ml-1 text-sm text-gray-500">（最近7天）</span>
      </h2>

      <div class="flex items-center space-x-1">
        <button @click="previousPage" :disabled="currentPage === 1" class="pagination-btn">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /></svg>
        </button>
        <span class="text-sm font-medium text-gray-600 w-8 text-center">{{ currentPage }}/{{ totalPages }}</span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /></svg>
        </button>
      </div>
    </div>

    <div class="grid grid-cols-3 gap-4">
      <div
        v-for="viewer in currentPageViewers"
        :key="viewer.id"
        class="viewer-grid-item group"
        @click="handleViewerClick(viewer.id)"
      >
        <div class="relative">
          <img
            :src="viewer.avatar"
            :alt="viewer.name"
            class="w-16 h-16 rounded-full object-cover border-2 border-white shadow-lg transition-transform duration-300 ease-in-out group-hover:scale-110"
          >
          <div v-if="viewer.gender"
               class="gender-badge absolute bottom-0 right-0 w-5 h-5 rounded-full flex items-center justify-center text-white text-xs shadow-md border-2 border-white"
               :class="viewer.gender === 'male' ? 'bg-blue-500' : 'bg-pink-400'">
            {{ viewer.gender === 'male' ? '♂' : '♀' }}
          </div>
        </div>
        <div class="text-center mt-2">
          <p class="font-semibold text-gray-800 text-sm truncate w-20">{{ viewer.name }}</p>
          <p class="text-xs text-gray-500 mt-0.5">{{ formatViewTime(viewer.viewTime) }}</p>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { viewersData } from '@/mock/user/viewersData.js';

export default {
  name: 'ViewersList',
  data() {
    return {
      viewers: viewersData,
      currentPage: 1,
      itemsPerPage: 6 // 3 columns * 2 rows
    };
  },
  computed: {
    totalPages() {
      if (!this.viewers || this.viewers.length === 0) return 1;
      return Math.ceil(this.viewers.length / this.itemsPerPage);
    },
    currentPageViewers() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      // Pad the array with empty objects if there are not enough viewers to fill the grid
      const pageData = this.viewers.slice(start, end);
      while(pageData.length < this.itemsPerPage && this.viewers.length > 0) {
        pageData.push({ id: `placeholder-${pageData.length}`, isEmpty: true });
      }
      return pageData;
    }
  },
  methods: {
    previousPage() {
      if (this.currentPage > 1) this.currentPage--;
    },
    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++;
    },
    handleViewerClick(viewerId) {
      if (typeof viewerId === 'string' && viewerId.startsWith('placeholder')) return;
      const route = this.$router.resolve({ name: 'user', params: { userId: viewerId } });
      window.open(route.href, '_blank');
    },
    formatViewTime(timeString) {
      if (!timeString) return '';
      const viewTime = new Date(timeString);
      const now = new Date();
      const diffSeconds = Math.round((now - viewTime) / 1000);

      if (diffSeconds < 60) return '刚刚';
      const diffMinutes = Math.round(diffSeconds / 60);
      if (diffMinutes < 60) return `${diffMinutes}分钟前`;
      const diffHours = Math.round(diffMinutes / 60);
      if (diffHours < 24) return `${diffHours}小时${diffMinutes % 60}分钟前`;

      const diffDays = Math.round(diffHours / 24);
      if (diffDays === 1) return '昨天';
      if (diffDays <= 7) return `${diffDays}天前`;

      // 格式化为 YYYY-MM-DD-HH:mm
      const year = viewTime.getFullYear();
      const month = String(viewTime.getMonth() + 1).padStart(2, '0');
      const day = String(viewTime.getDate()).padStart(2, '0');
      const hours = String(viewTime.getHours()).padStart(2, '0');
      const minutes = String(viewTime.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }
};
</script>

<style scoped>
.viewer-card {
  font-family: 'Inter', sans-serif;
}

/* Grid Item Styling */
.viewer-grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0.75rem; /* 12px */
  border-radius: 0.75rem; /* 12px */
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: rgba(249, 250, 251, 0.5); /* Semi-transparent background */
}

.viewer-grid-item:not([style*="visibility: hidden"]):hover {
  transform: translateY(-4px);
  background-color: white;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

/* Handle placeholder items */
.viewer-grid-item[data-empty="true"] {
  visibility: hidden;
  pointer-events: none;
}
/* A small trick in the template binds `isEmpty` to `data-empty` to make this selector work */
.viewer-grid-item[v-if="viewer.isEmpty"] {
  visibility: hidden;
}


/* Pagination Button Styling */
.pagination-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.75rem; /* 28px */
  height: 1.75rem; /* 28px */
  border-radius: 9999px; /* full */
  background-color: rgba(0, 0, 0, 0.05);
  color: #4b5563; /* text-gray-600 */
  transition: all 0.2s ease-in-out;
}

.pagination-btn:not(:disabled):hover {
  background-color: #10b981; /* emerald-500 */
  color: white;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.4);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>